package com.cskaoyan.service.impl;

import com.cskaoyan.bean.*;
import com.cskaoyan.bean.bo.GoodsCreateBo;
import com.cskaoyan.bean.vo.goods.*;
import com.cskaoyan.mapper.*;
import com.cskaoyan.service.GoodsService;
import com.cskaoyan.utils.QueryUserIdByUserNameUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 *
 * @author wangguangwu
 * @Auther: wangguangwu
 * @Date: 2021/04/08/22:16
 * @Description: 商品业务层实现类
 */
@Service
public class GoodsServiceImpl implements GoodsService {

    @Resource
    CskaoyanmallGoodsMapper goodsMapper;

    @Resource
    CskaoyanmallGoodsProductMapper goodsProductMapper;

    @Resource
    CskaoyanmallGoodsAttributeMapper goodsAttributeMapper;

    @Resource
    CskaoyanmallGoodsSpecificationMapper goodsSpecificationMapper;

    @Resource
    CskaoyanmallBrandMapper brandMapper;

    @Resource
    CskaoyanmallCategoryMapper categoryMapper;

    @Resource
    CskaoyanmallCommentMapper commentMapper;

    @Autowired
    CskaoyanmallUserMapper userMapper;

    @Autowired
    CskaoyanmallFootprintMapper footprintMapper;


    /**
     * 商品查询
     *
     * @param goodsRequestVo
     * @return
     */
    @Override
    public BaseData qureyGoods(GoodsRequestVo goodsRequestVo) {
        // 开启分页
        PageHelper.startPage(goodsRequestVo.getPage(), goodsRequestVo.getLimit());

        CskaoyanmallGoodsExample goodsExample = new CskaoyanmallGoodsExample();
        CskaoyanmallGoodsExample.Criteria criteria = goodsExample.createCriteria();
        // 设置排序条件
        goodsExample.setOrderByClause(goodsRequestVo.getSort() + " " + goodsRequestVo.getOrder());
        // 添加搜索条件
        // 名字搜索不为空时，添加名字搜索的条件
        if (goodsRequestVo.getName() != null && !"".equals(goodsRequestVo.getName())) {
            criteria.andNameLike("%" + goodsRequestVo.getName() + "%");
        }
        if (goodsRequestVo.getGoodsSn() != null && !"".equals(goodsRequestVo.getGoodsSn())) {
            criteria.andGoodsSnEqualTo(goodsRequestVo.getGoodsSn());
        }
        // 添加deleted=false，实现逻辑删除
        criteria.andDeletedEqualTo(false);

        // 执行搜索
        List<CskaoyanmallGoods> goods = goodsMapper.selectByExample(goodsExample);
        int total = goods.size();

        BaseData baseData = new BaseData(goods, total);
        return baseData;

    }


    @Override
    public BaseData queryComments(Integer page, Integer limit, String sort, String order) {
        CskaoyanmallCommentExample commentExample = new CskaoyanmallCommentExample();
        commentExample.setOrderByClause(sort + " " + order);
        PageHelper.startPage(page, limit);
        List<CskaoyanmallComment> comments = commentMapper.selectByExample(commentExample);
        PageInfo<CskaoyanmallComment> pageInfo = new PageInfo<>(comments);
        long total = pageInfo.getTotal();
        return new BaseData(comments, total);
    }

    /**
     * 评论删除
     * 完成
     *
     * @param comment
     */
    @Override
    public void deleteComment(CskaoyanmallComment comment) {
        comment.setDeleted(true);
        commentMapper.updateByPrimaryKey(comment);
    }


    @Override
    public GoodsDetailVo queryGoodsDetail(Integer id) {

        // 获取 goods
        CskaoyanmallGoods goods = goodsMapper.selectByPrimaryKey(id);

        // 获取 goodsAttribute
        CskaoyanmallGoodsAttributeExample goodsAttributeExample = new CskaoyanmallGoodsAttributeExample();
        goodsAttributeExample.createCriteria().andGoodsIdEqualTo(id).andDeletedEqualTo(false);
        List<CskaoyanmallGoodsAttribute> goodsAttributes = goodsAttributeMapper.selectByExample(goodsAttributeExample);

        // 获取指定 id 商品对应的category
        List<CskaoyanmallCategory> categories = categoryMapper.selectByPid(goods.getCategoryId());

        ArrayList<Integer> categoryIds = new ArrayList<>();
        if (categories != null) {
            for (CskaoyanmallCategory category : categories) {
                categoryIds.add(category.getId());
            }
        } else {
            categoryIds = null;
        }

        // 获得 goodsProduct
        CskaoyanmallGoodsProductExample goodsProductExample = new CskaoyanmallGoodsProductExample();
        goodsProductExample.createCriteria().andGoodsIdEqualTo(id).andDeletedEqualTo(false);
        List<CskaoyanmallGoodsProduct> goodsProducts = goodsProductMapper.selectByExample(goodsProductExample);

        // 获得 goodsSpecification
        CskaoyanmallGoodsSpecificationExample goodsSpecificationExample = new CskaoyanmallGoodsSpecificationExample();
        goodsSpecificationExample.createCriteria().andIdEqualTo(id).andDeletedEqualTo(false);
        List<CskaoyanmallGoodsSpecification> goodsSpecifications = goodsSpecificationMapper.selectByExample(goodsSpecificationExample);

        // 返回数据
        GoodsDetailVo goodsDetailVo = new GoodsDetailVo(goods, goodsAttributes, categoryIds, goodsProducts, goodsSpecifications);
        return goodsDetailVo;
    }

    /**
     * 商品上架
     *
     * @param goodsCreatBo 接收的数据
     * @return int 用数字表示成功与失败
     */
    @Override
    public int createGoods(GoodsCreateBo goodsCreatBo) {
        // 获得商品信息
        CskaoyanmallGoods goods = goodsCreatBo.getGoods();
        // 对商品必要条件进行判断
        if (goods == null || goods.getGoodsSn() == null || goods.getName() == null) {
            return 10000;
        }
        // 判断数据库中是否有同名的商品
        String name = goods.getName();
        CskaoyanmallGoodsExample goodsExample = new CskaoyanmallGoodsExample();
        goodsExample.createCriteria().andNameEqualTo(name).andDeletedEqualTo(false);
        List<CskaoyanmallGoods> goodsList = goodsMapper.selectByExample(goodsExample);
        for (CskaoyanmallGoods cskaoyanmallGoods : goodsList) {
            if (cskaoyanmallGoods.getId() != null) {
                return 20000;
            }
        }

        // 获得上架时间
        Date date = new Date();

        // 填充 goods 信息
        goods.setAddTime(date);
        goods.setUpdateTime(date);
        goods.setDeleted(false);
        goodsMapper.insert(goods);

        // 获得最新插入的 id
        int lastInsert = goodsMapper.selectLastInsert();
        goodsCreatBo.getGoods().setId(lastInsert);

        // 商品具体类型信息
        List<CskaoyanmallGoodsProduct> goodsProducts = goodsCreatBo.getGoodsProducts();
        if (goodsProducts != null) {
            for (CskaoyanmallGoodsProduct goodsProduct : goodsProducts) {
                goodsProduct.setGoodsId(lastInsert);
                goodsProduct.setDeleted(false);
                goodsProduct.setAddTime(date);
                goodsProduct.setUpdateTime(date);
                goodsProductMapper.insert(goodsProduct);
            }
        }

        // 商品参数
        List<CskaoyanmallGoodsAttribute> goodsAttributes = goodsCreatBo.getGoodsAttributes();
        if (goodsAttributes != null) {
            for (CskaoyanmallGoodsAttribute goodsAttribute : goodsAttributes) {
                goodsAttribute.setGoodsId(lastInsert);
                goodsAttribute.setAddTime(date);
                goodsAttribute.setUpdateTime(date);
                goodsAttribute.setDeleted(false);
                goodsAttributeMapper.insert(goodsAttribute);
            }
        }

        // 商品规格
        List<CskaoyanmallGoodsSpecification> goodsSpecifications = goodsCreatBo.getGoodsSpecifications();
        if (goodsSpecifications != null) {
            for (CskaoyanmallGoodsSpecification goodsSpecification : goodsSpecifications) {
                goodsSpecification.setDeleted(false);
                goodsSpecification.setGoodsId(lastInsert);
                goodsSpecification.setAddTime(date);
                goodsSpecification.setUpdateTime(date);
                goodsSpecificationMapper.insert(goodsSpecification);
            }
        }
        return 1;
    }


    /**
     * 商品更新
     * 完成
     * <p>
     * 有四个成员变量
     * 商品基本信息：goods
     * 商品参数：goodsAttributes
     * 商品货品表：goodsProducts
     * 商品规格表：goodsSpecifications
     * <p>
     * 所有成员变量都要修改updateTime
     *
     * @param goodsUpdateBo
     * @return int
     */
    @Override
    public int updateGoods(GoodsCreateBo goodsUpdateBo) {
        // 获得时间信息
        Date date = new Date();
        // 创建实例对象
        CskaoyanmallGoods goods = goodsUpdateBo.getGoods();
        List<CskaoyanmallGoodsProduct> newProducts = goodsUpdateBo.getGoodsProducts();
        List<CskaoyanmallGoodsAttribute> newAttributes = goodsUpdateBo.getGoodsAttributes();
        List<CskaoyanmallGoodsSpecification> newSpecifications = goodsUpdateBo.getGoodsSpecifications();

        // goods 直接修改 updateTime
        goodsUpdateBo.getGoods().setUpdateTime(date);
        goodsMapper.updateByPrimaryKey(goodsUpdateBo.getGoods());

        Integer goodsId = goodsUpdateBo.getGoods().getId();

        // product
        // 长度一直为 1，所以可以直接更新
        CskaoyanmallGoodsProduct newProduct = new CskaoyanmallGoodsProduct();
        if(newProducts!=null){
            for (CskaoyanmallGoodsProduct product : newProducts) {
                if(product!=null) {
                    newProduct = product;
                }
            }
        }
        CskaoyanmallGoodsProductExample goodsProductExample = new CskaoyanmallGoodsProductExample();
        goodsProductExample.createCriteria().andGoodsIdEqualTo(goodsId).andDeletedEqualTo(false);
        List<CskaoyanmallGoodsProduct> oldProducts = goodsProductMapper.selectByExample(goodsProductExample);
        for (CskaoyanmallGoodsProduct product : oldProducts) {
            product.setDeleted(false);
            product.setPrice(newProduct.getPrice());
            product.setNumber(newProduct.getNumber());
            product.setUpdateTime(date);
            goodsProductMapper.updateByPrimaryKey(product);
        }

        // attributes
        // 通过 goodsId 获取 attributes 的 id 集合
        CskaoyanmallGoodsAttributeExample goodsAttributeExample = new CskaoyanmallGoodsAttributeExample();
        goodsAttributeExample.createCriteria().andGoodsIdEqualTo(goodsId).andDeletedEqualTo(false);
        List<CskaoyanmallGoodsAttribute> oldAttributes = goodsAttributeMapper.selectByExample(goodsAttributeExample);

        if(newAttributes!=null){
            for (CskaoyanmallGoodsAttribute newAttribute : newAttributes) {
                newAttribute.setGoodsId(goodsId);
                if (newAttribute.getGoodsId() != null) {
                    newAttribute.setUpdateTime(date);
                    goodsAttributeMapper.updateByPrimaryKey(newAttribute);
                    System.out.println("updateAttr" + newAttribute);
                } else {
                    newAttribute.setAddTime(date);
                    newAttribute.setUpdateTime(date);
                    newAttribute.setDeleted(false);
                    goodsAttributeMapper.updateByPrimaryKey(newAttribute);
                    System.out.println("insertAttr" + newAttribute);
                }
            }
        }

        for (CskaoyanmallGoodsAttribute oldAttribute : oldAttributes) {
            oldAttribute.setDeleted(true);
            for (CskaoyanmallGoodsAttribute newAttribute : newAttributes) {
                if (newAttribute.getGoodsId().equals(oldAttribute.getGoodsId())) {
                    oldAttribute.setDeleted(false);
                    break;
                }
            }
            goodsAttributeMapper.updateByPrimaryKey(oldAttribute);
        }

        // specifications
        CskaoyanmallGoodsSpecificationExample goodsSpecificationExample = new CskaoyanmallGoodsSpecificationExample();
        goodsSpecificationExample.createCriteria().andIdEqualTo(goodsId).andDeletedEqualTo(false);
        List<CskaoyanmallGoodsSpecification> oldSpecifications = goodsSpecificationMapper.selectByExample(goodsSpecificationExample);

        if(newSpecifications!=null){
            for (CskaoyanmallGoodsSpecification newSpecification : newSpecifications) {
                newSpecification.setGoodsId(goodsId);
                if (newSpecification.getGoodsId() != null) {
                    newSpecification.setUpdateTime(date);
                    goodsSpecificationMapper.updateByPrimaryKey(newSpecification);
                } else {
                    newSpecification.setAddTime(date);
                    newSpecification.setUpdateTime(date);
                    newSpecification.setDeleted(false);
                    goodsSpecificationMapper.insert(newSpecification);
                }
            }
        }

        for (CskaoyanmallGoodsSpecification oldSpecification : oldSpecifications) {
            oldSpecification.setDeleted(true);
            for (CskaoyanmallGoodsSpecification newSpecification : newSpecifications) {
                if (oldSpecification.getId().equals(newSpecification.getId())) {
                    oldSpecification.setDeleted(false);
                    break;
                }
            }
            goodsSpecificationMapper.updateByPrimaryKey(oldSpecification);
        }
        return 1;

    }

    /**
     * 商品品牌
     *
     * @return CatAndBrandVo
     */
    @Override
    public CatAndBrandVo queryCatAndBrand() {
        List<BrandVo> brandVos = brandMapper.selectAll();
        List<CategoryVo> categoryVos = categoryMapper.selectAll();
        return new CatAndBrandVo(brandVos, categoryVos);
    }

    /**
     * 删除商品
     */
    @Override
    public void deleteGoods(CskaoyanmallGoods goods) {
        // 1. 获取时间信息
        Date date = new Date();
        // 2. 获得商品 id
        Integer goodsId = goods.getId();
        // 3. 修改商品信息
        goods.setUpdateTime(date);
        goods.setDeleted(true);
        goodsMapper.updateByPrimaryKey(goods);
        // 4. 修改商品货品表
        CskaoyanmallGoodsProductExample goodsProductExample = new CskaoyanmallGoodsProductExample();
        goodsProductExample.createCriteria().andGoodsIdEqualTo(goodsId).andDeletedEqualTo(false);
        List<CskaoyanmallGoodsProduct> goodsProducts = goodsProductMapper.selectByExample(goodsProductExample);
        if (goodsProducts != null) {
            for (CskaoyanmallGoodsProduct goodsProduct : goodsProducts) {
                goodsProduct.setUpdateTime(date);
                goodsProduct.setDeleted(true);
                goodsProductMapper.updateByExample(goodsProduct, goodsProductExample);
            }
        }

        // 5. 修改商品参数表
        CskaoyanmallGoodsAttributeExample goodsAttributeExample = new CskaoyanmallGoodsAttributeExample();
        goodsAttributeExample.createCriteria().andIdEqualTo(goodsId).andDeletedEqualTo(false);
        List<CskaoyanmallGoodsAttribute> goodsAttributes = goodsAttributeMapper.selectByExample(goodsAttributeExample);
        if (goodsAttributes != null) {
            for (CskaoyanmallGoodsAttribute goodsAttribute : goodsAttributes) {
                goodsAttribute.setUpdateTime(date);
                goodsAttribute.setDeleted(true);
                goodsAttributeMapper.updateByExample(goodsAttribute, goodsAttributeExample);
            }
        }

        // 6. 修改商品规格表
        CskaoyanmallGoodsSpecificationExample goodsSpecificationExample = new CskaoyanmallGoodsSpecificationExample();
        goodsSpecificationExample.createCriteria().andIdEqualTo(goodsId).andDeletedEqualTo(false);
        List<CskaoyanmallGoodsSpecification> goodsSpecifications = goodsSpecificationMapper.selectByExample(goodsSpecificationExample);
        if (goodsSpecifications != null) {
            for (CskaoyanmallGoodsSpecification goodsSpecification : goodsSpecifications) {
                goodsSpecification.setUpdateTime(date);
                goodsSpecification.setDeleted(true);
                goodsSpecificationMapper.updateByExample(goodsSpecification, goodsSpecificationExample);
            }
        }
    }


}
